<?php
class system_db_table_select extends system_db_select {
	protected $_info;
	protected $_integrityCheck = true;
	protected $_table;
	
	public function __construct(system_db_table_abstract $table) {
		parent::__construct($table->getAdapter());
		$this->setTable($table);
	}
	
	public function setTable($table) {
		//$this->_adapter = $table->getAdapter();
		$this->_info = $table->info();
		$this->_table = $table;
		
		return $this;
	}
	public function getTable() {
		return $this->_table;
	}
	
	public function setIntegrityCheck($flag = true) {
		$this->_integrityCheck = $flag;
		return $this;
	}
	
	public function isReadOnly() {
		$readOnly = false;
		$fields = $this->getPart(system_db_table_select::COLUMNS);
		$cols = $this->_info[system_db_table_abstract::COLS];
		
		if(!count($fields)) {
			return $readOnly;
		}
		
		foreach($fields as $columnEntry) {
			$column = $columnEntry[1];
			$alias = $columnEntry[2];
			
			if($alias!==null) {
				$column = $alias;
			}
			
			switch(true) {
				case ($column==self::SQL_WILDCARD):
					break;
				
				case ($column instanceof system_db_expr):
				case (!in_array($column, $cols)):
					$readOnly = true;
					break 2;
			}
		}
		
		return $readOnly;
	}
	
	public function from($name, $cols = self::SQL_WILDCARD, $schema = null) {
		if($name instanceof system_db_table_abstract) {
			$info = $name->info();
			$name = $info[system_db_table_abstract::NAME];
			if(isset($info[system_db_table_abstract::SCHEMA])) {
				$schema = $info[system_db_table_abstract::SCHEMA];
			}
		}
		
		return $this->joinInner($name, null, $cols, $schema);
	}
	
	public function assemble() {
		$fields = $this->getPart(system_db_table_select::COLUMNS);
		$primary = $this->_info[system_db_table_abstract::NAME];
		$schema = $this->_info[system_db_table_abstract::SCHEMA];
		
		if(count($this->_parts[self::UNION])==0) {
			
			// If no fields are specified we assume all fields from primary table
			if(!count($fields)) {
				$this->from($primary, self::SQL_WILDCARD, $schema);
				$fields = $this->getPart(system_db_table_select::COLUMNS);
			}
			
			$from = $this->getPart(system_db_table_select::FROM);
			
			if($this->_integrityCheck!==false) {
				foreach($fields as $columnEntry) {
					list($table, $column) = $columnEntry;
					
					// Check each column to ensure it only references the primary table
					if($column) {
						if(!isset($from[$table])||$from[$table]['tableName']!=$primary) {
							throw new system_db_table_select_exception('Select query cannot join with another table');
						}
					}
				}
			}
		}
		
		return parent::assemble();
	}
}